/* eslint-disable @typescript-eslint/no-explicit-any */
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { isFunction, isString } from 'lodash-es';
import {
  IDrawerOptions,
  IModalOptions,
  IOverlayContainer,
} from '@ibiz-template/runtime';
import { h, resolveComponent, ConcreteComponent } from 'vue';
import { OverlayController } from '@ibiz-template/vue3-components';
import { createDrawer } from '../app-drawer/app-drawer-component';
import { createModal } from '../app-modal/app-modal-component';

function resolveComponentOrStr(component: unknown): string | ConcreteComponent {
  return isString(component)
    ? resolveComponent(component)
    : (component as ConcreteComponent);
}

/**
 * 自定义模态控制器
 *
 * @export
 * @class CustomOverlayController
 * @extends {OverlayController}
 */
export class CustomOverlayController extends OverlayController {
  /**
   * 抽屉容器
   *
   * @protected
   * @type {(IOverlayContainer | undefined)}
   * @memberof OverlayController
   */
  protected drawerContainer: IOverlayContainer | undefined;

  /**
   * 创建抽屉
   *
   * @param {unknown} component
   * @param {IParams} [props]
   * @param {IDrawerOptions} [opts]
   * @return {*}  {*}
   * @memberof CustomOverlayController
   */
  createDrawer(
    component: unknown,
    props?: IParams,
    opts?: IDrawerOptions,
  ): any {
    if (!this.drawerContainer) {
      this.drawerContainer = createDrawer(
        isFunction(component)
          ? component
          : () => h(resolveComponentOrStr(component), { ...props }),
        opts,
        props,
      );
    } else {
      (this.drawerContainer as any).updateProps(props);
    }
    this.drawerContainer.onWillDismiss().then(() => {
      this.drawerContainer = undefined;
    });
    return this.drawerContainer;
  }

  /**
   * 创建模态
   *
   * @param {unknown} component
   * @param {IParams} [props]
   * @param {IModalOptions} [opts]
   * @return {*}  {*}
   * @memberof CustomOverlayController
   */
  createModal(component: unknown, props?: IParams, opts?: IModalOptions): any {
    return createModal(
      isFunction(component)
        ? component
        : () => h(resolveComponentOrStr(component), { ...props }),
      opts,
    );
  }
}
